import 'dart:io';
import 'package:flutter/material.dart';
import 'package:csv/csv.dart';

class TestBomRemoval extends StatelessWidget {
  const TestBomRemoval({Key? key}) : super(key: key);

  Future<void> _testBomRemoval(BuildContext context) async {
    try {
      // 读取测试文件
      final file = File('D:\\000\\my-web\\test_words_final.csv');
      String content = await file.readAsString(encoding: utf8);
      
      // 检查是否包含BOM标记
      bool hasBom = content.startsWith('\uFEFF');
      
      // 去除BOM标记（如果存在）
      if (hasBom) {
        content = content.substring(1);
        print('已去除CSV文件的BOM标记');
      }

      // 解析CSV
      List<List<dynamic>> csvTable = const CsvToListConverter().convert(content);
      
      // 显示结果
      String message = '';
      message += '原始文件' + (hasBom ? '包含' : '不包含') + 'BOM标记\n';
      message += '解析后的CSV表头: ${csvTable[0].join(", ")}\n';
      message += '解析后的第一行数据: ${csvTable[1].join(", ")}\n';
      message += '总共解析了 ${csvTable.length} 行数据';
      
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(message), duration: const Duration(seconds: 10))
      );
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('测试失败: $e'))
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('测试BOM标记去除')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: () => _testBomRemoval(context),
              child: const Text('测试BOM标记去除'),
            ),
          ],
        ),
      ),
    );
  }
}